package com.ygxsk.carhome.ui.park;

import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.park.keyboard.InputViewSelectKeyboard;
import com.park.keyboard.OnInputChangedListener;
import com.park.keyboard.PopupKeyboard;
import com.park.keyboard.view.InputView;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.event.EventParkingInside;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.DoubleClickListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.listener.MyKeyboardListener;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.utils.VehiclePlateNoUtil;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2024/1/6  14:12
 * @Description:绑定车牌 提交车牌
 */
public class ParkingBundleActivity extends ErrorActivity implements ErrorParentExtraSingle {

    @BindView(R.id.btnsubmit)
    RoundTextView btnSubmit;

    @BindView(R.id.input_view_park)
    InputView mInputView;


    //车辆的车牌的填写描述
    @BindView(R.id.radiogroupcartypepark)
    RadioGroup radioGroupCarType;

    //普通的车
    @BindView(R.id.radiaobuttoncarnomalpark)
    RadioButton radioButtonCarNomal;

    //新能源车
    @BindView(R.id.radiaobuttoncarnewenergypark)
    RadioButton radioButtonCarNewEnergy;

    /**
     * 提交车位上传的ID信息
     */
    private String parkingSpaceIdPass;
    private PopupKeyboard mPopupKeyboard;
    //车牌号
    private String vehicleNo_upLoad = "";

    private MaterialDialog materialDialogSubmit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initViews();

    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mInputView != null) {
            // 默认选中第一个车牌号码输入框
            mInputView.performFirstFieldView();
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_parking_bundle;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.title_carplace_bundle));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        //这里右上角没有东西的
        toolbarHelper.setLayoutRight(true, 0, "", null);

        //添加潜在客户的按钮
//        toolbarHelper.setLayoutRight(true, 0, "添加", new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                //快速双加的限制，
//                // : 2023-07-11 16:18 添加预约维保的信息，到提交表单页面；
//                Bundle extra_bundle = new Bundle();
////                ActivityUtils.startActivity(extra_bundle, LeadAddSubmitActivity.class);
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        //retain

    }

    @Override
    protected void initViews() {


        //默认普通车选中
        if (radioButtonCarNomal != null) {
            radioButtonCarNomal.setChecked(true);
            radioButtonCarNomal.setTextColor(ColorUtils.getColor(R.color.headmanblue));
        }

        if (radioButtonCarNewEnergy != null) {
            radioButtonCarNewEnergy.setChecked(false);
            radioButtonCarNewEnergy.setTextColor(ColorUtils.getColor(R.color.dark));
        }


        //键盘布局
//        mInputView = (InputView) this.findViewById(R.id.input_view);
        //做键盘绑定
        // 创建弹出键盘
        mPopupKeyboard = new PopupKeyboard(ParkingBundleActivity.this, new MyKeyboardListener() {
            @Override
            public void doSomeThing() {

                method_check_licenseNumber();

            }
        });
        // 弹出键盘内部包含一个KeyboardView，在此绑定输入两者关联。
        mPopupKeyboard.attach(mInputView, ParkingBundleActivity.this);
        //设置默认是【河北省】
        mPopupKeyboard.getKeyboardEngine().setLocalProvinceName(getString(R.string.hebei_province));
        //放开第八个？
//        mInputView.set8thVisibility(true);
        // 隐藏确定按钮? 不要隐藏
//        mPopupKeyboard.getKeyboardEngine().setHideOKKey(mHideOKKey);

        //输入变更回调接口
        mPopupKeyboard.getController().addOnInputChangedListener(new OnInputChangedListener() {
            @Override
            public void onChanged(String number, boolean isCompleted) {

                //监听变更为新能源
                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "打印输入的车牌号码-->" + number);
//                mPopupKeyboard.getController().updateNumberLockType(number,true);

                if (isCompleted) {

                    method_check_licenseNumber();

                    mPopupKeyboard.dismiss(ParkingBundleActivity.this);
                }


            }

            @Override
            public void onCompleted(String number, boolean isAutoCompleted) {
                mPopupKeyboard.dismiss(ParkingBundleActivity.this);
            }
        });

        //---------------------------------------------------------------------------------------------

        if (radioGroupCarType != null) {

            radioGroupCarType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {

                    if (checkedId == R.id.radiaobuttoncarnomalpark) {

                        //选中了普通车牌，那么不用锁定是新能源.

                        try {

                            radioButtonCarNomal.setChecked(true);
                            radioButtonCarNomal.setTextColor(ColorUtils.getColor(R.color.headmanblue));
//                            radioButtonCarNomal.setTextColor(ColorUtils.getColor(R.color.blueskpress));

                            radioButtonCarNewEnergy.setChecked(false);
                            radioButtonCarNewEnergy.setTextColor(ColorUtils.getColor(R.color.dark));

                            //如果用户都填写了车牌号，刚好是8位，那么删除掉最后一位
                            int length = mInputView.getNumber().length();

                            if (length > 7) {
                                //删除掉最后一个
                                mInputView.removeLastCharOfNumber();
                            }

                            //do
                            if (mPopupKeyboard.getController() != null) {

                                mPopupKeyboard.getController()
                                        .setDebugEnabled(true)
                                        .updateNumberLockType(mInputView.getNumber(), false, InputViewSelectKeyboard.KEYBOARD_SHOW_YES.getIndex());

                            }

                        } catch (Exception e) {
                            //catch
                            e.printStackTrace();
                        }


                    } else if (checkedId == R.id.radiaobuttoncarnewenergypark) {

                        //选中的是新能源的按钮

                        try {

                            radioButtonCarNomal.setChecked(false);
                            radioButtonCarNomal.setTextColor(ColorUtils.getColor(R.color.dark));

                            radioButtonCarNewEnergy.setChecked(true);
                            radioButtonCarNewEnergy.setTextColor(ColorUtils.getColor(R.color.headmanblue));

                            //do
                            //锁定是新能源
                            if (mPopupKeyboard.getController() != null) {

                                mPopupKeyboard.getController()
                                        .setDebugEnabled(true)
                                        .updateNumberLockType(mInputView.getNumber(), true, InputViewSelectKeyboard.KEYBOARD_SHOW_YES.getIndex());

                            }

                        } catch (Exception e) {
                            //catch
                            e.printStackTrace();
                        }

                    }

                }
            });
        }


        btnSubmit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (!DoubleClickListener.isFastDoubleClick()) {

                    if (materialDialog != null && materialDialog.isShowing()) {
                        materialDialog.dismiss();
                    }

                    //LogUtils.d("itchen---添加的车牌信息是-->" + etPlateNumber.getText().toString().trim());

                    /*new SpanUtils().append("您的车牌:")
                            .setForegroundColor(ColorUtils.getColor(R.color.dark))
                            .append(etPlateNumber.getText().toString().trim())
                            .setForegroundColor(ColorUtils.getColor(R.color.dark))
                            .create();*/

                    //校验输入车牌
                    vehicleNo_upLoad = mInputView.getNumber();

                    if (TextUtils.isEmpty(vehicleNo_upLoad)) {

                        CommUtils.checkDialog(mAlertView);
                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_input_car_number), true);
                        mAlertView.show();

                        return;
                    }

                    //如果填写了车牌，而恰恰又不是正确的车牌，那么需要校验下：
                    if (!TextUtils.isEmpty(vehicleNo_upLoad)) {
                        //验证车牌的正确性
                        if (VehiclePlateNoUtil.getVehiclePlateNo(vehicleNo_upLoad) == null) {
                            CommUtils.checkDialog(mAlertView);
                            mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_input_carnumersure), true);
                            mAlertView.show();
                            return;
                        }
                    }


                    if (!TextUtils.isEmpty(vehicleNo_upLoad)) {

                        //这里准备做个二次确认弹窗 ，认真看清 自己即将添加的车牌之后，再提交添加。
                        materialDialogSubmit = new MaterialDialog.Builder(ParkingBundleActivity.this)
                                .title(getResources().getString(R.string.sure_add_car_upload))//确认添加
                                .content(vehicleNo_upLoad)//车牌号
                                //.content(new SpanUtils()
                                //.append("您的车牌:")//
                                //.setForegroundColor(ColorUtils.getColor(R.color.dark))//
                                //.append(etPlateNumber.getText().toString().trim())//
                                //.setForegroundColor(ColorUtils.getColor(R.color.buttonnomcolor))//
                                //.setBold()
                                //.create())//
                                .contentColor(ColorUtils.getColor(R.color.buttonnomcolor))//
                                .positiveText(getResources().getString(R.string.add_sure_stringvalue))//确认添加
                                .positiveColor(ColorUtils.getColor(R.color.buttonnomcolor))//
                                .negativeText(getResources().getString(R.string.updatebuttoncancel))
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                        method_uploadBundle();

                                    }
                                }).onNegative(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                        if (materialDialogSubmit != null && materialDialogSubmit.isShowing()) {
                                            materialDialogSubmit.dismiss();
                                        }

                                    }
                                }).dismissListener(new DialogInterface.OnDismissListener() {
                                    @Override
                                    public void onDismiss(DialogInterface dialog) {

                                        if (materialDialogSubmit != null && materialDialogSubmit.isShowing()) {
                                            materialDialogSubmit.dismiss();
                                        }

                                    }
                                }).canceledOnTouchOutside(false)
                                .show();

                        //设置两个按钮内容
                        materialDialogSubmit.getTitleView().setTextSize(16);//设置标题字体大小
                        materialDialogSubmit.getContentView().setTextSize(18);//设置文本内容大小
                        materialDialogSubmit.getContentView().setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            materialDialogSubmit.getContentView().setLetterSpacing(0.5f);
                        }

                        materialDialogSubmit.getActionButton(DialogAction.POSITIVE).setTextSize(15);
                        materialDialogSubmit.getActionButton(DialogAction.NEGATIVE).setTextSize(15);

                    } else {

                        ToastUtils.make().setGravity(Gravity.CENTER, 0, 0);
                        //请输入车牌号
                        ToastUtils.showShort(getResources().getString(R.string.intput_carnumber_keyword));

                    }

                }

            }
        });
        //testArray();

    }

    //校验车牌的通用方法
    private void method_check_licenseNumber() {
        //检验车牌的正确定
        vehicleNo_upLoad = mInputView.getNumber().trim();

        if (!TextUtils.isEmpty(vehicleNo_upLoad)) {
            //验证车牌的正确性
            if (VehiclePlateNoUtil.getVehiclePlateNo(vehicleNo_upLoad) == null) {
                CommUtils.checkDialog(mAlertView);
                mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_input_carnumersure), true);
                mAlertView.show();
                return;
            }

        } else {
            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "输入的车牌号是空值");
        }
    }

    @Override
    protected void gainDatas() {

        //retain

    }

    //提交绑定：
    private void method_uploadBundle() {

//        map.put("communityId", _sessionErrorActivity.getCommunityId());
//        map.put("shopInfoId", _sessionErrorActivity.getShopInfoId());
//
//        map.put("CarNo", _carNumber);
//        map.put("parkingSpaceId", _parkingSpaceId);

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.CarNo, vehicleNo_upLoad);
        map.put(Parameterkey.parkingSpaceId, parkingSpaceIdPass);

//        map.put(Parameterkey.status, RepairStatusUpLoadType.STATE_HAS_DISPATCH.getIndex());
//        map.put(Parameterkey.handleStatus, status_upLoad);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_ADDCARNOFORREMOTE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.addCarNoForRemote_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .addCarNoForRemote(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(ParkingBundleActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
//                        methodNotSuccessData(what_method, serverCode, serverMessage);
                        CommUtils.checkMaterialDialog(materialDialog);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_SUBMIT);

                    }
                }).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        CommUtils.checkMaterialDialog(materialDialog);

                        //是添加成功
//                        String addSuccess = getResources().getString(R.string.addsucceepark);
//                        PopTip.show(addSuccess).iconSuccess();

                        //通知主页列表刷新
                        methodSubmitSuccess(ParkingBundleActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {

                                EventParkingInside eventParkingInside = new EventParkingInside();
                                eventParkingInside.setMessage(ExtraValue.EVENTBUS_PARKING_OUTSIDE_ADD);
                                EventBus.getDefault().post(eventParkingInside);

                                methodBack();

                            }
                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        CommUtils.checkMaterialDialog(materialDialog);
                        //页面报错；
                        function_apiException(apiException);
                    }
                });

    }

    @Override
    protected void methodBack() {
        methodBackFinish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            if (mPopupKeyboard.isShown()) {
                mPopupKeyboard.dismiss(ParkingBundleActivity.this);
                return false;
            }

//            else {
//                mPopupKeyboard.show(SmartGoOutActivity.this);
//            }

//            if (keyboardUtil.isShow()) {
//                keyboardUtil.hideKeyboard();
//                return false;
//            }

        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        CommUtils.checkMaterialDialog(materialDialogSubmit);

    }

    @Override
    public void processExtraData() {

        //共同处理获取到的Bundle数据
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {
            parkingSpaceIdPass = bundle.getString(ExtraKey.EXTRA_PARKINGSPACEID);
        }

    }


}